#!/bin/sh
# Tuxlocator gpsdeamon
# (c) 2007 by Rein Velt / http://geo.velt.org
# Published under the terms and conditions
# of the General Public License (GPL)

gps=/dev/ttyUSB0
stty -F $gps ospeed 4800

#initialize /var
echo "?" > /var/gps_latitude
echo "?" > /var/gps_longitude
echo "?" > /var/gps_altitude
echo "?" > /var/gps_sats_in_view
echo "?" > /var/gps_heading
echo "?" > /var/gps_speed
echo GPS daemon started 
while true;
do
awk -F , '$1=="$GPGGA" {print}' $gps | head -n 1 > /var/gps_GPGGA
awk -F , '$1=="$GPRMC" {print}' $gps | head -n 1 > /var/gps_GPRMC    
awk -F , '$1=="$GPRMC" {print $3}' /var/gps_GPRMC > /var/gps_valid
good_pos=$(cat /var/gps_valid)
case $good_pos in
        V)      #echo GPS Data is NOT VALID !!!
                awk -F , '$1=="$GPGGA" {print $8}' /var/gps_GPGGA > /var/gps_sats_in_view 
                ;;                      
        A)      # echo GPS Data is valid
                awk -F , '$1=="$GPGGA" {print $3 $4}' /var/gps_GPGGA > /var/gps_latitude 
                awk -F , '$1=="$GPGGA" {print $5 $6}' /var/gps_GPGGA > /var/gps_longitude
		lon="`cat /var/gps_longitude`"
		lat="`cat /var/gps_latitude`"
		#convert coordinates to dd format
		lonDeg="`echo $lon | awk '{ printf("%s",substr($1,1,3)) }'`"
		lonMin="`echo $lon | awk '{ printf("%s",substr($1,4,7)) }'`"
		latDeg="`echo $lat | awk '{ printf("%s",substr($1,1,2)) }'`"    
                latMin="`echo $lat | awk '{ printf("%s",substr($1,3,7)) }'`"
		lonDD="`echo $lonDeg $lonMin | awk '{ printf("%1.5f",int($1)+($2/60.0)) }'`"
		latDD="`echo $latDeg $latMin | awk '{ printf("%1.5f",int($1)+($2/60.0)) }'`"
                 
		#echo "(" $lonDD "," $latDD ") <=> (" $lon "," $lat ")" 
		echo $latDD > /var/gps_latitude_dd
		echo $lonDD > /var/gps_longitude_dd

		awk -F , '$1=="$GPGGA" {print $10 $11}' /var/gps_GPGGA > /var/gps_altitude
                awk -F , '$1=="$GPGGA" {print $8}' /var/gps_GPGGA > /var/gps_sats_in_view                   
                awk -F , '$1=="$GPRMC" {print $9}' /var/gps_GPRMC > /var/gps_heading
                awk -F , '$1=="$GPRMC" {print $8}' /var/gps_GPRMC > /var/gps_speed
                ;;
        esac
     

        sleep 10
done
exit 0
